function parseParam(param, key) {
	var paramStr = "";
	if(param instanceof String || param instanceof Number || param instanceof Boolean) {
		paramStr += "&" + key + "=" + encodeURIComponent(param);
	} else {
		if(param.length <= 0) {
			paramStr += '&' + key + "=[]";
		} else {
			$.each(param,
				function(i) {
					var k = key == null ? i : key + (param instanceof Array ? "[" + i + "]" : "." + i);
					paramStr += '&' + parseParam(this, k);
				});
		}

	}
	return paramStr.substr(1);
}

function Api() {
	this.token = "";
	this.URL = "https://cp899.kosunmobile.com/Mobile";

}

Api.prototype.sort = function(data) {
	var a = [];
	$.each(data, function(key, val) {
		a[a.length] = key;
	});
	a.sort();
	var tmp = {};
	$.each(a, function(i, key) {
		tmp[key] = data[key]
	});
	return tmp
}

Api.prototype.sort1 = function(arys) {
	//先用Object内置类的keys方法获取要排序对象的属性名，再利用Array原型上的sort方法对获取的属性名进行排序，newkey是一个数组
	var newkey = Object.keys(arys).sort();　　
	//console.log('newkey='+newkey);
	var newObj = {}; //创建一个新的对象，用于存放排好序的键值对
	for(var i = 0; i < newkey.length; i++) {
		//遍历newkey数组
		newObj[newkey[i]] = arys[newkey[i]];
		//向新创建的对象中按照排好的顺序依次增加键值对

	}
	return newObj; //返回排好序的新对象
}

// 计算授权
Api.prototype.auth = function(param) {
	var tmp = JSON.parse(JSON.stringify(param)) // 一定要复制一个新的对象，不然会修改原来的对象
	if(tmp["order_list"] !== undefined) {
		tmp["order_list"][0] = this.sort(tmp["order_list"][0])
		tmp["order_list"] = JSON.stringify(tmp["order_list"])
	}

	var a = this.sort(tmp)
	urlparam = decodeURIComponent(parseParam(a))
	return md5(urlparam + "kosun.net");
}

Api.prototype.post = function(param, callback) {
	var headers = {
		"Content-Type": "application/json; charset=utf-8",
		"authorization": "",
		"accept": "application/json",
		"user-agent": "ios",
		"token": ""
	}
	headers["authorization"] = this.auth(param);
	headers["token"] = this.token;
	plus.nativeUI.showWaiting();
	$.ajax({
		//请求类型，这里为POST
		type: 'POST',
		//你要请求的api的URL
		url: this.URL,
		//是否使用缓存
		cache: false,
		//数据类型，这里我用的是json
		dataType: "json",
		//必要的时候需要用JSON.stringify() 将JSON对象转换成字符串
		data: JSON.stringify(param),
		//添加额外的请求头
		headers: headers,
		async: false,
		//请求成功的回调函数
		success: function(data, status) {
			callback(data, status);
		},
	});
	plus.nativeUI.closeWaiting();
}

// 测试函数
Api.prototype.login = function() {
	// 判断当前是否有登入
	if(this.islogin()) {
		return;
	}

	var reval = undefined;
	var s = undefined
	var param = {
		"act": 10022,
		"is_special_agent": 0,
		"password": "abc1234",
		"user_name": "woddle"
	}
	this.post(param, function(data, status) {
		reval = data;
		console.info(JSON.stringify(data))
	});
	if(reval["status"] === 0) {
		this.token = reval["token"]
		localStorage.setItem("token", this.token);
	} else {
		this.post(param, function(data, status) {
			reval = data;
			console.info(JSON.stringify(data))
		});
	}

}

Api.prototype.islogin = function() {
	var reval = undefined;
	var param = {
		'act': 10034
	};
	this.post(param, function(data) {
		reval = data;
	});
	return reval["status"] === 0;
}

Api.prototype.exit = function() {
	var param = {
		"act": "10037"
	}
	var reval = undefined;
	this.post(param, function(data) {
		reval = data;
	});

}

Api.prototype.get_now_issue = function() {
	var param = {
		"act": 10003,
		"lottery_id": "1"
	};

	var reval = undefined;
	this.post(param, function(data) {
		reval = data;
	});
	return reval;
}

Api.prototype.get_last_20 = function() {
	param = {
		"act": 10005,
		"lottery_id": "1"
	}
	var ret;
	this.post(param, function(data) {
		ret = data;
	});
	console.info(JSON.stringify(ret))
	return ret
}

Api.prototype.get_last_100 = function() {
	param = {
		"act": 10017,
		"lottery_id": "1"
	}
	var ret;
	this.post(param, function(data) {
		ret = data;
	});

	return ret
}

Api.prototype.buy = function(play = "后三组三", mode = 1) {
	var table = {
		"后三组三": 27,
		"后三组六": 28,
		"前三组三": 39,
		"前三组六": 40,
		"中三组三": 33,
		"中三组六": 34
	}
	var totalmoney = {
		0: {
			"money": 240,
			"nums": 120
		},
		1: {
			"money": 180,
			"nums": 90
		}
	}

	// 获取最新期数
	var issue = this.get_now_issue()["issue_no"]

	// 得到type
	var type = table[play] % 2
	var money = totalmoney[type].money * Math.pow(10, (mode - 1) * -1)
	var nums = totalmoney[type].nums
	alert("type:" + type + ",money:" + money + ",nums:" + nums)

	var param = {
		"act": 10006,
		"lottery_id": "1", // 彩票类型
		"order_list": [{
			"play_id": table[play].toString(), // 玩法类型 27：后三组三  28：后三组六 39：前三组三 40：前三组六  33：中三组三 34：中三组六
			"content": "0,1,2,3,4,5,6,7,8,9",
			"mode": 1, // 百分比类型 1：1  2:0.1  3：0.01
			"point": "0.0",
			"nums": nums, // 所选的组合个数
			"price": 2, // 每组的钱数 只能是整数
			"money": money // 投入钱数
		}],
		"plan_list": [],
		"win_stop": 0,
		"issue_no": issue
	}
	var ret;
	this.post(param, function(data, status) {
		ret = data;
	});
	console.info(ret["status"] + ret["message"])
	if(ret["status"] === 9000003) {
		console.info("重新登入")
		this.login();

		this.post(param, function(data, status) {
			ret = data;
		});
	}

	return ret;
}

Date.prototype.Format = function(fmt) { //author: meizz 
	var o = {
		"M+": this.getMonth() + 1, //月份 
		"d+": this.getDate(), //日 
		"h+": this.getHours(), //小时 
		"m+": this.getMinutes(), //分 
		"s+": this.getSeconds(), //秒 
		"q+": Math.floor((this.getMonth() + 3) / 3), //季度 
		"S": this.getMilliseconds() //毫秒 
	};
	if(/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for(var k in o)
		if(new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
}

var api = new Api();